package com.deshan.websys.code.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deshan.websys.code.mapper.CorporationMapper;
import com.deshan.websys.code.mapper.PmsPageSetItemMapper;
import com.deshan.websys.code.mapper.PmsPageSetMapper;
import com.deshan.websys.code.model.Blogroll;
import com.deshan.websys.code.model.Corporation;
import com.deshan.websys.code.model.PmsPageSet;
import com.deshan.websys.code.model.PmsPageSetItem;
import com.deshan.websys.code.model.SmsHomeAdvertise;
import com.deshan.websys.code.model.SocialInfo;
import com.deshan.websys.code.model.vo.CorporationVO;
import com.deshan.websys.code.model.vo.CustomersVO;
import com.deshan.websys.code.model.vo.GoodsVO;
import com.deshan.websys.code.service.BlogrollService;
import com.deshan.websys.code.service.CmsPageSetService;
import com.deshan.websys.code.service.CorporationService;
import com.deshan.websys.code.service.CustomersService;
import com.deshan.websys.code.service.GoodsService;
import com.deshan.websys.code.service.SmsHomeAdvertiseService;
import com.deshan.websys.code.service.SocialInfoService;
import com.deshan.websys.code.utils.BeanUtil;
import com.deshan.websys.code.utils.Constant;

import cn.hutool.core.collection.CollUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class CmsPageSetServiceImpl extends ServiceImpl<CorporationMapper, Corporation> implements CmsPageSetService {

	private final PmsPageSetItemMapper pmsPageSetItemMapper;

	private final PmsPageSetMapper pmsPageSetMapper;

	private final SmsHomeAdvertiseService advertiseService;

	private final SocialInfoService socialInfoService;

	private final GoodsService goodsService;

	private final CorporationService corporationService;

	private final BlogrollService blogrollService;

	@Override
	public HashMap getPageInfo(int tag) {
		List<PmsPageSet> pagelist = pmsPageSetMapper.selectList(null);
		List<PmsPageSetItem> datalist = pmsPageSetItemMapper.selectList(null);
		HashMap<String, Object> datamap = new HashMap<>();
		HashMap<String, Object> itemMap = new HashMap<>();
		for (PmsPageSetItem item : datalist) {
			String columid = item.getColumid();
			int group = item.getGroup();
			String element = item.getElement();
			String content = item.getContent();
			if ("LOGO".equals(element)) {
				if (tag == -1) {
					content = "http://192.168.1.9:8001/api/upload/20241029/logo.jpg";
				}
			}
			if ("URL".equals(element)) {
				if (tag == -1) {
					content = "http://192.168.1.9:8002";
				}
			}

			Object object = datamap.get(columid);
			Object itemObject = itemMap.get(columid + "-" + group);
			if (itemObject == null) {
				HashMap sjmap = new LinkedHashMap();
				sjmap.put(element, content);
				itemMap.put(columid + "-" + group, sjmap);
			} else {
				if (itemObject instanceof HashMap) {
					((HashMap) itemObject).put(element, content);
				}
			}
		}

		HashMap rootmap = pageint(itemMap);
		return rootmap;

	}

	@Override
	public Object editPageInfo(PmsPageSetItem pmsPageSetItem) {
		Integer id = pmsPageSetItem.getItemid();
		int result = 0;
		if (id == null) {
			result = pmsPageSetItemMapper.insert(pmsPageSetItem);
		} else {
			PmsPageSetItem descpmsPageSetItem = pmsPageSetItemMapper.selectById(id);
			try {
				BeanUtil.copyNotNullProperties(descpmsPageSetItem, pmsPageSetItem);
				result = pmsPageSetItemMapper.updateById(descpmsPageSetItem);
			} catch (Exception ex) {

			}

		}
		return result;

	}

	//
//    public JSONObject getPageInfo1(int tag){
//        String homepagepath="C://homepage.xml";
//        try{
//            homepagepath= ApplicationUtils.getProperty("oss.homepagepath", "upload");
//        }catch (Exception ex){
//
//        }
//        Document doc=null;
//        JSONObject rootObj = new JSONObject();
//        try {
//
//            File f = new File(homepagepath);
//            InputStream in = new FileInputStream(f);
//            Reader reader = new InputStreamReader(in, "UTF-8"); // 确保这里的编码与XML文件的编码一致
////            in.close();
//            SAXReader saxReader = new SAXReader();
//            saxReader.setEncoding("UTF-8");
//            doc = saxReader.read(reader);
//        }catch (Exception ex) {
//
//            try {
//                FileInputStream fileInputStream = new FileInputStream(homepagepath);
//
//                byte[] buffer = new byte[2048];
//                int readBytes = 0;
//                StringBuilder stringBuilder = new StringBuilder();
//                while ((readBytes = fileInputStream.read(buffer)) > 0) {
//                    stringBuilder.append(new String(buffer, 0, readBytes));
//                }
//                fileInputStream.close();
//            String Content=new String (stringBuilder.toString().getBytes(),"UTF-8");
////                String Content = new String(stringBuilder.toString().getBytes());
//                int begin = Content.indexOf("<?xml");
//                String xmls = Content.substring(begin);
//                doc = DocumentHelper.parseText(xmls);
//            }catch (Exception ex1) {
//            }finally {
//
//            }
//        }
//            Element root = doc.getRootElement();
//            List<Element> elements= root.elements();
//               for(Element element: elements ){
//                   String name= element.getQName().getName();
//                   List<Element> itemlist= element.elements("ITEAM");
//                   JSONArray jsonArray=  initJSON(itemlist,tag);
//                   rootObj.put(name,jsonArray);
//               }
//
//         return rootObj;
//
//    }
//
//    private JSONArray initJSON(List<Element> itemlist,int tag ){
//        JSONArray jsonArray =new JSONArray();
//        for(Element itemElemet:itemlist){
//            JSONObject itemobject=new JSONObject();
//            for (Iterator i = itemElemet.elementIterator(); i.hasNext();) {
//                Element element = (Element) i.next();
//
//                String name= element.getQName().getName();
//                String value= element.getText();
//                if("LOGO".equals(name)){
//                    if(tag==-1){
//                        value="http://192.168.1.9:8001/api/upload/20241029/logo.jpg";
//                    }
//                }
//                if("URL".equals(name)){
//                    if(tag==-1){
//                        value="http://192.168.1.9:8002";
//                    }
//                }
//
//
//                itemobject.put(name,value);
//            }
//            jsonArray.add(itemobject);
//        }
//        return jsonArray;
//    }
	private HashMap pageint(HashMap<String, Object> itemMap) {
		HashMap<String, ArrayList> rootMap = new HashMap<>();
		Iterator it = itemMap.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			String[] colums = key.split("-");
			ArrayList list = rootMap.get(colums[0]);
			if (list == null) {
				list = new ArrayList();
				list.add(itemMap.get(key));
				rootMap.put(colums[0], list);
			} else {
				list.add(itemMap.get(key));
			}
		}
		return rootMap;
	}

	@Override
	public CorporationVO getPageInfo_new(String legalCode) {
//        CorporationVO corporationVO = new CorporationVO();
//        Corporation corporation = getOne(Wrappers.lambdaQuery(Corporation.class).eq(Corporation::getCorCode, legalCode));
		CorporationVO corporationVO = corporationService.getCorporationInfoByLegalCode(legalCode);
		if (Objects.isNull(corporationVO)) {
			log.info("getPageInfo_new()---法人编码:{},没有对应的法人信息", legalCode);
			return null;
		}
//        BeanUtils.copyProperties(corporation, corporationVO);
		corporationVO.setSocialInfoList(getSocialInfoListByLegalCode(legalCode));
		corporationVO.setBlogrollList(getBlogrollListByLegalCode(legalCode));
		List<GoodsVO> goods = getGoodsListByLegalCode(legalCode);
		if (CollUtil.isNotEmpty(goods)) {
			corporationVO.setGoodsList(goods);
			corporationVO.setAdvertiseList(
					getAdvertiseListByGoodsId(goods.stream().map(GoodsVO::getId).collect(Collectors.toList())));
		}
		return corporationVO;
	}

	private List<SmsHomeAdvertise> getAdvertiseListByGoodsId(List<String> gids) {
		return advertiseService.list(Wrappers.lambdaQuery(SmsHomeAdvertise.class).eq(SmsHomeAdvertise::getStatus, Constant.ADVERTISE_UPLINE)
				.in(SmsHomeAdvertise::getGid, gids));
	}

	private List<Blogroll> getBlogrollListByLegalCode(String legalCode) {
		return blogrollService.list(Wrappers.lambdaQuery(Blogroll.class).eq(Blogroll::getLegalCode, legalCode)
				.orderByDesc(Blogroll::getHits));
	}

	private List<GoodsVO> getGoodsListByLegalCode(String legalCode) {
		return goodsService.getGoodsListByLegalCode(legalCode);
	}

	private List<SocialInfo> getSocialInfoListByLegalCode(String legalCode) {
		return socialInfoService.list(Wrappers.lambdaQuery(SocialInfo.class).eq(SocialInfo::getLegalCode, legalCode));
	}


}
